package controller.dao;

import model.*;

import java.util.*;

import javax.persistence.*;

public class Dao_Card {
	EntityManager manager;
	public boolean save(Card card) {
		try	{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(card);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public List<Card> listAll(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT c FROM Card c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Card> Cards =  query.getResultList();
		manager.close();
		return Cards;
	}
	
	public List<Card> listAll(int inicio, int quant){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT c FROM Card c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Card> cards =  query.setMaxResults(quant).setFirstResult(inicio).getResultList();
		manager.close();
		return cards;
	}
	
	public boolean update(Card card){
		try{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(card);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public boolean delete(Card card){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(card);
			manager.getTransaction().commit();
			manager.close();				
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public Card list(int id){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();	
			Card card = manager.find(Card.class, id);
			manager.close();
			return card;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
	public Long totalCards(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT count(c) FROM Card c where c.active = 1" );
		Long total = (Long) query.getSingleResult();
		manager.close();
		return total;
	}
}
